#include <iostream>
#include <unistd.h>
#include <cstring>
#include <sys/types.h>
#include <sys/wait.h>
#include <cstdio>
using namespace std;

int main()
{
    // child -> write parent -> read
    int fd[2];
    int res = pipe(fd); // pipe只用于父子进程
    if (res == -1)
    {
        cerr << "Pipe Fail!" << endl;
        exit(1);
    }
    pid_t pid = fork();
    if (pid == 0)
    {
        // 子进程
        close(fd[0]);
        //const char *msg = "Hello parent! I am Child process!";
        //int cnt = 10; // 写入10条数据
        char ch = 'c';
        int count = 0;
        while (1)
        {
            //     ssize_t n = write(fd[1], msg, strlen(msg));
            //     if (n == -1)
            //     {
            //         cerr << "Write Msg Fail!" << endl;
            //         exit(2);
            //     }
            //     sleep(1);

            //写端一直写，读端不读取，写端把管道写满，写端就会被挂起
            write(fd[1], &ch, 1);
            count++;
            //cout << "count: " << count << endl;
            printf("count: %d\n", count);
        }
        close(fd[1]);
        exit(0);
    }
    // 父进程
    // 如果close在前面代表读端已经关闭，写端进程直接被杀死
    close(fd[1]);
    waitpid(pid, nullptr, 0); 
    close(fd[0]);
    exit(0);

    //close(fd[1]);
    // char buffer[2048];
    // while (true)
    // {
    //     ssize_t n = read(fd[0], buffer, sizeof(buffer) - 1);
    //     if (n > 0)
    //     {
    //         buffer[n] = 0;
    //         cout << "parent read: " << buffer << endl;
    //     }
    //     else if (n == 0)
    //     {
    //         cout << "read end!" << endl;
    //         exit(0);
    //     }
    //     else
    //     {
    //         cerr << "read error" << endl;
    //         break;
    //     }
    // }
    //读端已经关闭，写端进程会被OS杀死，看会收到哪个信号?
    //close(fd[0]);
   // int status = 0;
    // exit(0);
    // 等待子进程退出
    //waitpid(pid, &status, 0);
    //cout << "Parent Get Signal is: " << status & 0x7F;
   // printf("parent get singal is: %d\n", status & 0x7F);  // 13 -> sigpipe 信号
    return 0;
}
